package com.xb.cloud.common.util;

import java.io.IOException;
import java.io.InputStream;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.SecureRandom;
import java.security.cert.Certificate;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

import com.alibaba.fastjson.JSON;

import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class OKhttpsUtils {

	private static final OkHttpClient client;
	static {
		SSLSocketFactory ssfFactory = null;
		X509TrustManager trustManager = new MyTrustManager();

		try {
			// File file = new File("d:/var/csdn.cer");
			// FileInputStream inputStream = new FileInputStream(file);
			// trustManager = trustManagerForCertificates(inputStream);

			SSLContext sc = SSLContext.getInstance("TLS");
			sc.init(null, new TrustManager[] { trustManager }, new SecureRandom());
			ssfFactory = sc.getSocketFactory();

		} catch (Exception e) {
			e.printStackTrace();
		}

		client = new OkHttpClient.Builder().sslSocketFactory(ssfFactory, trustManager)
				.hostnameVerifier(new TrustAllHostnameVerifier()).build();
	}

	public static void main(String[] args) throws IOException {
		String url = "https://www.12306.cn/mormhweb/";
		OKhttpsUtils.doPost(url, null);
	}

	public static String doPost(String url, Map<String, String> params) throws IOException {
		FormBody.Builder builder = new FormBody.Builder();
		for (String key : params.keySet()) {
			builder.add(key, params.get(key));
		}
		FormBody formBody = builder.build();
		final Request request = new Request.Builder().url(url).post(formBody).build();
		Response response = client.newCall(request).execute();
		if (response.isSuccessful()) {
			return response.body().string();
		} else {
			throw new IOException("Unexpected code " + response);
		}
	}

	public static void doGet() throws IOException {
		String url = "https://blog.csdn.net/xiaoleiacmer/article/details/51685170";

		final Request request = new Request.Builder().url(url).build();
		Response response = client.newCall(request).execute();
		if (response.isSuccessful()) {
			System.out.println(response.body().string());
		} else {
			System.out.println("error");
		}
	}

	private static X509TrustManager trustManagerForCertificates(InputStream in) throws GeneralSecurityException {
		CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
		Collection<? extends Certificate> certificates = certificateFactory.generateCertificates(in);
		if (certificates.isEmpty()) {
			throw new IllegalArgumentException("expected non-empty set of trusted certificates");
		}

		// Put the certificates a key store.
		char[] password = "password".toCharArray(); // Any password will work.
		KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); // 这里添加自定义的密码，默认
		try {
			keyStore.load(null, password);
		} catch (IOException e) {
			e.printStackTrace();
		}

		int index = 0;
		for (Certificate certificate : certificates) {
			String certificateAlias = Integer.toString(index++);
			keyStore.setCertificateEntry(certificateAlias, certificate);
		}

		// Use it to build an X509 trust manager.
		KeyManagerFactory keyManagerFactory = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
		keyManagerFactory.init(keyStore, password);
		TrustManagerFactory trustManagerFactory = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		trustManagerFactory.init(keyStore);
		TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
		if (trustManagers.length != 1 || !(trustManagers[0] instanceof X509TrustManager)) {
			throw new IllegalStateException("Unexpected default trust managers:" + Arrays.toString(trustManagers));
		}
		return (X509TrustManager) trustManagers[0];
	}

	private static class MyTrustManager implements X509TrustManager {
		public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
		}

		public X509Certificate[] getAcceptedIssuers() {
			return new X509Certificate[] {};
		}
	}

	private static class TrustAllHostnameVerifier implements HostnameVerifier {
		@Override
		public boolean verify(String hostname, SSLSession session) {
			return true;
		}
	}

}
